import { Directive, HostListener, Input, ElementRef, Renderer2 } from '@angular/core';
import { DragDropService } from '../drag-drop.service';

@Directive({
  selector: '[taskDraggable][dragTag][dragData][draggedClass]' // 元素可以写多个属性
})
export class DragDirective {
  private _isDraggable = false; // 设置是否可拖拽,可以动态使用
  @Input('taskDraggable') //  使用taskDraggable属性时默认会调用这个set方法
  set isDraggable(val: boolean) { // set get方法 TypeScript的方法
    this._isDraggable = val;
    this.rd.setAttribute(this.el.nativeElement, 'draggable', `${val}`);
  }
  get isDraggable() {
    return this._isDraggable;
  }
  // 拖拽要添加的样式
  @Input() draggedClass: string; // 输入性属性
  @Input() dragTag: string;
  @Input() dragData: any;
  constructor(private el: ElementRef, private rd: Renderer2, private service: DragDropService) { } // 要改变DOM元素就必须有ElementRef和Renderer2
  // 监听事件
  @HostListener('dragstart', ['$event'])
  onDragStart(ev: Event) {
    if (this.el.nativeElement === ev.target) {
      this.rd.addClass(this.el.nativeElement, this.draggedClass);
      this.service.setDragData({ tag: this.dragTag, data: this.dragData });
    }
  }
  @HostListener('dragend', ['$event'])
  onDragend(ev: Event) {
    if (this.el.nativeElement === ev.target) {
      this.rd.removeClass(this.el.nativeElement, this.draggedClass);
    }
  }
}
